<?php
/**
 * PhExecutionTimeMeasure
 * Class for the execution time measurement
 * 
 * This package is distributed under the
 * GNU General Public License v.3.
 * See the LICENSE.txt file for details.
 * 
 * @package   Phlame
 * @author    Phlegma <phlegma@pheelgood.net>
 * @copyright 2008 by Phlegma
 * @link 	  http://ugamela-forum.pheelgood.net
 * @since     01.05.2008
 * @version   0.1
 * @access    public
 * 
 * Last modify: 13.06.2008
 */

class PhExecutionTimeMeasure
{
	//const WRONG_DATA_INPUT_MUST_BE_TIME_OBJECT = 'wrong data input. awaiting time object';

	protected $_starttime;
	protected $_endtime;
	/**
	 * Types times array
	 * @var array (types=>time objects)
	 */
	protected $_tt = array();
	protected $_classname;

	public function __construct()
	{
		$this->_classname = get_class($this);
		$this->start();
	}

	public function start()
	{
		$this->_starttime = microtime(true);
	}

	public function is_running()
	{
		return isset($this->_endtime)?false:true;
	}

	public function end()
	{
		$this->_endtime = microtime(true);
	}

	protected function __set($type, PhExecutionTimeMeasure $value)
	{
		/*if (!is_object($value) || $this->_classname != get_class($value))
		{
			throw new Exception(self::WRONG_DATA_INPUT_MUST_BE_TIME_OBJECT);
		}
		if (isset($this->_tt[$type]))
		{
		//return $this->_tt[$type];
		}
		else
		{*/
		$this->_tt[$type] = //clone
		$value;
		//}
	}
	
	public function __call($type, $params)
	{
		if (!isset($this->_tt[$type]))
		{
			$this->_tt[$type] = new $this->_classname;
			if ($params[0]==true)
			{
				$this->_tt[$type]->start();
			}
			if ($params[1]==true)
			{
				$this->_tt[$type]->end();
			}
			return true;
		}
	}
	
	protected function __get($type)
	{
		if (!isset($this->_tt[$type]))
		{
			$this->_tt[$type] = new $this->_classname;
		}
		return $this->_tt[$type];
	}

	public function calculate_times($calc_types = true)
	{
		$times_array = array($this->_endtime-$this->_starttime);
		if ($calc_types)
		{
			foreach ($this->_tt as $type => $time_object)
			{
				$array = $time_object->calculate_times(false);
				$times_array[$type] = $array[0];
			}
		}
		return $times_array;
	}
	
	protected function __toString() {
		$this->end();
		$t = $this->calculate_times();
		return implode(',',$t);
	}

}

?>